package edu.dhbw.mannheim;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
 
public class Search extends HttpServlet {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}
 
	public void destroy() {
 
	}
 
	/**
	 * AJAX function searches for a blog containing a certain string
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Key blogKey = KeyFactory.createKey("blog", "blogblogblog");
		Query query = new Query("post", blogKey).addSort("date", Query.SortDirection.DESCENDING);
		List<Entity> posts = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
		String searchString = request.getParameter("searchString");
		String returnString = "";
		int found = 0;
		for(int i = 0; i<posts.size() && found <10;i++)
		{
			String content = ((Text)posts.get(i).getProperty("content")).getValue();
			String topic = (String)posts.get(i).getProperty("topic");
			String blogID = (String)posts.get(i).getProperty("internalID");
			String contentTopic = content+" "+topic;
			if(contentTopic.toLowerCase().contains(searchString.toLowerCase()))
			{
				found++;
				if(returnString!="")
					returnString+="<TRENNSYMBOL>";
				returnString +=blogID+" <b>"+topic +"</b> "+Post.htmlSubString(content, 200, true);
			}				
		}
		out.println(returnString);
	}
}